package com.acmen.easyapi.repository;

import com.acmen.easyapi.util.UUID;
import com.alibaba.fastjson.JSON;
import com.acmen.easyapi.dbcp.JdbcService;
import com.acmen.easyapi.model.App;
import com.acmen.easyapi.util.StringUtil;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

;

@Component
public class AppRepository {
    @Resource
    private JdbcService jdbcService;
    private final static String QUERY_LIST_SQL = "select id,name,port,note,route,update_dt updateDt from t_app order by idx";
    private final static String CHECK_BY_NAME_SQL = "select 1 from t_app where name=?";
    private final static String QUERY_BY_NAME_SQL = "select * from t_app where name=?";

    private final static String INSERT_SQL = "insert into t_app(id,name,port,note,route,create_dt,update_dt,response_codes,validator_notes,data_generator_notes) values(?,?,?,?,?,?,?,?,?,?)";
    private final static String UPDATE_SQL = "update t_app set port=?,note=?,update_dt=?,response_codes=?,validator_notes=?,data_generator_notes=?,route=? where name=?";

    public boolean exits(String appName){
        Map dataMap = jdbcService.selectOne(CHECK_BY_NAME_SQL, new Object[]{appName});
        return dataMap!=null;
    }

    public boolean create(App app){
        app.setId(UUID.genUUID32());
        Object[] args = {app.getId(), app.getName(),app.getPort(),app.getNote(),app.getRoute(), LocalDateTime.now(),LocalDateTime.now(),toJSONString(app.getResponseCodes()),toJSONString(app.getValidatorNotes()),toJSONString(app.getDataGeneratorNotes())};
       return jdbcService.update(INSERT_SQL, args)>0;
    }

    public boolean update(App app){
        Object[] args = {app.getPort(),app.getNote(),LocalDateTime.now(),toJSONString(app.getResponseCodes()),toJSONString(app.getValidatorNotes()),toJSONString(app.getDataGeneratorNotes()),app.getRoute(), app.getName()};
       return jdbcService.update(UPDATE_SQL,args)>0;
    }

    public List<App> getAll() {
        return jdbcService.selectList(QUERY_LIST_SQL, new Object[]{},App.class);
    }

    public App selectByName(String name) {
        return jdbcService.selectOne(QUERY_BY_NAME_SQL, new Object[]{name},App.class);
    }

    public String toJSONString(Object obj){
        if(StringUtil.isEmpty(obj)){
            return null;
        }
        return JSON.toJSONString(obj);
    }
}
